package ro.gateway.aida.charts;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import ro.gateway.aida.db.PersistenceManager;
import ro.gateway.aida.db.PersistenceToken;
import ro.gateway.aida.search.ResultsFormat;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: Jun 17, 2004
 * Time: 6:55:55 PM
 * To change this template use File | Settings | File Templates.
 */
public class ChartRenderer {
	static void make_chart(HttpServletRequest request,
					    ServletContext application,
					    ChartWizzard$ActionForm form)
		  throws IOException, ChartException {
		PersistenceToken token = PersistenceManager.tokenLookup(application);

		// generate chart
		ResultsFormat results_format = new ResultsFormat();
		if (!"prjcounter".equals(form.y_axe_criteria)) {
			results_format.addColumn(form.y_axe_criteria);
		} else {
			results_format.addColumn(ResultsFormat.PROJECT_ID_COLUMN);
		}

		String x_axe_criteria_ = form.x_axe_criteria;
		if (form.x_axe_criteria != null && form.x_axe_criteria.startsWith("year#")) {
			x_axe_criteria_ = form.x_axe_criteria.substring(5);
		}
		String x_axe_group_criteria_ = form.x_axe_group_criteria;
		if (form.x_axe_group_criteria != null && form.x_axe_group_criteria.startsWith("year#")) {
			x_axe_group_criteria_ = form.x_axe_group_criteria.substring(5);
		}

		if (x_axe_criteria_ != null) {
			results_format.addColumn(x_axe_criteria_);
		} else {
			throw new RuntimeException("x_axe_criteria wrong");
		}
		if (x_axe_group_criteria_ != null) {
			results_format.addColumn(x_axe_group_criteria_);
		}
//		System.out.println(results_format.getFormat());

		try {
			form.search_results = ChartWizard$Action.performSearch(token, form.search_query, results_format);
//			System.out.println("Search for charts performed:" + form.search_results.size());
		} catch (Exception ex) {
			ex.printStackTrace();
			return;
		}

		if (form.chart_type.startsWith("bar")) {
			BarChartRenderer.make_barchart(request, application, form);
		} else if (form.chart_type.startsWith("pie")) {
			PieChartRenderer.make_piechart(request, application, form);
		} else if ("time".equals(form.chart_type)) {
			TimeChartRenderer.make_linechart(request, application, form);
		}
	}
}
